using Hospital.API.Dto;
using Hospital.API.HospitalServices.IServices;
using Hospital.Domain;
using Hospital.ErrorCode;
using Hospital.Infrastructrue;
using Microsoft.EntityFrameworkCore;

namespace Hospital.API.HospitalServices.Services
{
    public class WorkflowServices : IWorkflowServices
    {
        private readonly IBaseRepository<ServiceAuditWorkflow> _workflowRepository;
        private readonly IBaseRepository<ServiceAuditStep> _stepRepository;
        private readonly IBaseRepository<ServiceType> _serviceTypeRepository;
        private readonly IBaseRepository<Doctor> _doctorRepository;
        private readonly ILogger<WorkflowServices> _logger;

        public WorkflowServices(
            IBaseRepository<ServiceAuditWorkflow> workflowRepository,
            IBaseRepository<ServiceAuditStep> stepRepository,
            IBaseRepository<ServiceType> serviceTypeRepository,
            IBaseRepository<Doctor> doctorRepository,
            ILogger<WorkflowServices> logger)
        {
            _workflowRepository = workflowRepository;
            _stepRepository = stepRepository;
            _serviceTypeRepository = serviceTypeRepository;
            _doctorRepository = doctorRepository;
            _logger = logger;
        }

        public async Task<APIResult<WorkflowDto>> CreateWorkflow(CreateWorkflowDto createWorkflowDto)
        {
            try
            {
                // 验证医生是否存在
                var doctor = await _doctorRepository.Getlist()
                    .Where(d => d.Id == createWorkflowDto.DoctorId && !d.IsDeleted)
                    .FirstOrDefaultAsync();

                if (doctor == null)
                {
                    return new APIResult<WorkflowDto>
                    {
                        Code = ResultCode.Error,
                        Message = "医生不存在"
                    };
                }

                // 获取服务类型
                var serviceTypes = await _serviceTypeRepository.Getlist()
                    .Where(st => createWorkflowDto.ServiceTypeIds.Contains(st.Id) && !st.IsDeleted)
                    .ToListAsync();

                if (!serviceTypes.Any())
                {
                    return new APIResult<WorkflowDto>
                    {
                        Code = ResultCode.Error,
                        Message = "未找到有效的服务类型"
                    };
                }

                // 创建工作流
                var workflow = WorkflowService.CreateServiceAuditWorkflow(createWorkflowDto.DoctorId, serviceTypes);

                // 保存工作流
                await _workflowRepository.AddAsyn(workflow);

                // 更新步骤的工作流ID并保存
                foreach (var step in workflow.Steps)
                {
                    step.WorkflowId = workflow.Id;
                    await _stepRepository.AddAsyn(step);
                }

                // 转换为DTO
                var workflowDto = new WorkflowDto
                {
                    Id = workflow.Id,
                    DoctorId = workflow.DoctorId,
                    DoctorName = doctor.Name,
                    Status = workflow.Status,
                    CreatedTime = workflow.CreatedTime,
                    CompletedTime = workflow.CompletedTime,
                    Auditor = workflow.Auditor,
                    Remarks = workflow.Remarks,
                    Steps = workflow.Steps.Select(s => new WorkflowStepDto
                    {
                        Id = s.Id,
                        WorkflowId = s.WorkflowId,
                        ServiceName = s.ServiceName,
                        AuditStatus = s.AuditStatus,
                        Remarks = s.Remarks,
                        AuditTime = s.AuditTime,
                        Auditor = s.Auditor,
                        StepOrder = s.StepOrder
                    }).ToList()
                };

                return new APIResult<WorkflowDto>
                {
                    Code = ResultCode.Success,
                    Message = "工作流创建成功",
                    Data = workflowDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工作流失败");
                return new APIResult<WorkflowDto>
                {
                    Code = ResultCode.Error,
                    Message = "创建工作流失败: " + ex.Message
                };
            }
        }

        public async Task<APIResult<APIPaging<List<WorkflowDto>>>> GetWorkflowList(WorkflowQueryDto queryDto)
        {
            try
            {
                // 构建查询条件
                var query = _workflowRepository.Getlist()
                    .Include(w => w.Doctor)
                    .Include(w => w.Steps)
                    .Where(w => !w.IsDeleted);

                // 应用查询条件
                if (queryDto.DoctorId.HasValue)
                {
                    query = query.Where(w => w.DoctorId == queryDto.DoctorId.Value);
                }

                if (!string.IsNullOrEmpty(queryDto.Status))
                {
                    query = query.Where(w => w.Status == queryDto.Status);
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页
                var pageIndex = queryDto.PageIndex <= 0 ? 1 : queryDto.PageIndex;
                var pageSize = queryDto.PageSize <= 0 ? 10 : queryDto.PageSize;
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                // 获取分页数据
                var workflows = await query
                    .OrderByDescending(w => w.CreatedTime)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                // 转换为DTO
                var workflowDtos = workflows.Select(w => new WorkflowDto
                {
                    Id = w.Id,
                    DoctorId = w.DoctorId,
                    DoctorName = w.Doctor?.Name,
                    Status = w.Status,
                    CreatedTime = w.CreatedTime,
                    CompletedTime = w.CompletedTime,
                    Auditor = w.Auditor,
                    Remarks = w.Remarks,
                    Steps = w.Steps.Where(s => !s.IsDeleted).Select(s => new WorkflowStepDto
                    {
                        Id = s.Id,
                        WorkflowId = s.WorkflowId,
                        ServiceName = s.ServiceName,
                        AuditStatus = s.AuditStatus,
                        Remarks = s.Remarks,
                        AuditTime = s.AuditTime,
                        Auditor = s.Auditor,
                        StepOrder = s.StepOrder
                    }).OrderBy(s => s.StepOrder).ToList()
                }).ToList();

                // 构建分页结果
                var pagingResult = new APIPaging<List<WorkflowDto>>
                {
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    Data = workflowDtos
                };

                return new APIResult<APIPaging<List<WorkflowDto>>>
                {
                    Code = ResultCode.Success,
                    Message = "获取工作流列表成功",
                    Data = pagingResult
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流列表失败");
                return new APIResult<APIPaging<List<WorkflowDto>>>
                {
                    Code = ResultCode.Error,
                    Message = "获取工作流列表失败: " + ex.Message
                };
            }
        }

        public async Task<APIResult<WorkflowDto>> GetWorkflowById(int id)
        {
            try
            {
                var workflow = await _workflowRepository.Getlist()
                    .Include(w => w.Doctor)
                    .Include(w => w.Steps)
                    .Where(w => w.Id == id && !w.IsDeleted)
                    .FirstOrDefaultAsync();

                if (workflow == null)
                {
                    return new APIResult<WorkflowDto>
                    {
                        Code = ResultCode.Error,
                        Message = "工作流不存在"
                    };
                }

                var workflowDto = new WorkflowDto
                {
                    Id = workflow.Id,
                    DoctorId = workflow.DoctorId,
                    DoctorName = workflow.Doctor?.Name,
                    Status = workflow.Status,
                    CreatedTime = workflow.CreatedTime,
                    CompletedTime = workflow.CompletedTime,
                    Auditor = workflow.Auditor,
                    Remarks = workflow.Remarks,
                    Steps = workflow.Steps.Where(s => !s.IsDeleted).Select(s => new WorkflowStepDto
                    {
                        Id = s.Id,
                        WorkflowId = s.WorkflowId,
                        ServiceName = s.ServiceName,
                        AuditStatus = s.AuditStatus,
                        Remarks = s.Remarks,
                        AuditTime = s.AuditTime,
                        Auditor = s.Auditor,
                        StepOrder = s.StepOrder
                    }).OrderBy(s => s.StepOrder).ToList()
                };

                return new APIResult<WorkflowDto>
                {
                    Code = ResultCode.Success,
                    Message = "获取工作流详情成功",
                    Data = workflowDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流详情失败，工作流ID: {WorkflowId}", id);
                return new APIResult<WorkflowDto>
                {
                    Code = ResultCode.Error,
                    Message = "获取工作流详情失败: " + ex.Message
                };
            }
        }

        public async Task<APIResult<bool>> UpdateWorkflowStep(UpdateWorkflowStepDto updateStepDto)
        {
            try
            {
                var step = await _stepRepository.Getlist()
                    .Where(s => s.Id == updateStepDto.StepId && !s.IsDeleted)
                    .FirstOrDefaultAsync();

                if (step == null)
                {
                    return new APIResult<bool>
                    {
                        Code = ResultCode.Error,
                        Message = "工作流步骤不存在"
                    };
                }

                // 更新步骤
                step.AuditStatus = updateStepDto.AuditStatus;
                step.Remarks = updateStepDto.Remarks;
                step.Auditor = updateStepDto.Auditor;
                step.AuditTime = DateTime.Now;

                await _stepRepository.Update(step);

                // 获取工作流并检查是否需要更新状态
                var workflow = await _workflowRepository.Getlist()
                    .Include(w => w.Steps)
                    .Where(w => w.Id == step.WorkflowId && !w.IsDeleted)
                    .FirstOrDefaultAsync();

                if (workflow != null)
                {
                    // 更新工作流状态
                    WorkflowService.CompleteWorkflow(workflow);
                    await _workflowRepository.Update(workflow);
                }

                return new APIResult<bool>
                {
                    Code = ResultCode.Success,
                    Message = "更新工作流步骤成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工作流步骤失败");
                return new APIResult<bool>
                {
                    Code = ResultCode.Error,
                    Message = "更新工作流步骤失败: " + ex.Message
                };
            }
        }

        public async Task<APIResult<List<ServiceType>>> GetServiceTypes()
        {
            try
            {
                // 首先尝试从数据库获取服务类型
                var serviceTypes = await _serviceTypeRepository.Getlist()
                    .Where(st => !st.IsDeleted && st.IsEnabled)
                    .OrderBy(st => st.SortOrder)
                    .ToListAsync();

                // 如果数据库中没有服务类型数据，则使用默认的服务类型数据
                if (!serviceTypes.Any())
                {
                    serviceTypes = ServiceTypeData.GetDefaultServiceTypes();
                    
                    // 将默认服务类型保存到数据库
                    foreach (var serviceType in serviceTypes)
                    {
                        await _serviceTypeRepository.AddAsyn(serviceType);
                    }
                    
                    _logger.LogInformation("已初始化默认服务类型数据");
                }

                return new APIResult<List<ServiceType>>
                {
                    Code = ResultCode.Success,
                    Message = "获取服务类型列表成功",
                    Data = serviceTypes
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取服务类型列表失败");
                
                // 如果数据库操作失败，返回默认服务类型数据
                try
                {
                    var defaultServiceTypes = ServiceTypeData.GetDefaultServiceTypes();
                    return new APIResult<List<ServiceType>>
                    {
                        Code = ResultCode.Success,
                        Message = "获取默认服务类型列表成功",
                        Data = defaultServiceTypes
                    };
                }
                catch (Exception fallbackEx)
                {
                    _logger.LogError(fallbackEx, "获取默认服务类型列表也失败");
                    return new APIResult<List<ServiceType>>
                    {
                        Code = ResultCode.Error,
                        Message = "获取服务类型列表失败: " + ex.Message
                    };
                }
            }
        }
    }
} 